package cn.itrigger.dynamic.sql.select;

import cn.itrigger.dynamic.sql.render.RenderingStrategy;
import cn.itrigger.dynamic.sql.select.render.SelectRenderer;
import cn.itrigger.dynamic.sql.select.render.SelectStatementProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * @author admin
 * @date 2018/9/25
 **/
public class SelectModel {
    private List<QueryExpressionModel> queryExpressions;
    private OrderByModel orderByModel;

    private SelectModel(Builder builder) {
        this.queryExpressions = Objects.requireNonNull(builder.queryExpressions);
        this.orderByModel = builder.orderByModel;
    }

    public <R> Stream<R> mapQueryExpressions(Function<QueryExpressionModel, R> mapper) {
        return queryExpressions.stream().map(mapper);
    }

    public Optional<OrderByModel> getOrderByModel() {
        return Optional.ofNullable(orderByModel);
    }

    public SelectStatementProvider render(RenderingStrategy renderingStrategy) {
        return SelectRenderer.withSelectModel(this)
                .withRenderingStrategy(renderingStrategy)
                .build()
                .render();
    }

    public static Builder withQueryExpressions(List<QueryExpressionModel> queryExpressions) {
        return new Builder().withQueryExpressions(queryExpressions);
    }

    public static class Builder {
        private List<QueryExpressionModel> queryExpressions = new ArrayList<>();
        private OrderByModel orderByModel;

        public Builder withQueryExpressions(List<QueryExpressionModel> queryExpressions) {
            this.queryExpressions = queryExpressions;
            return this;
        }

        public Builder withOrderByModel(OrderByModel orderByModel) {
            this.orderByModel = orderByModel;
            return this;
        }

        public SelectModel build() {
            return new SelectModel(this);
        }
    }
}
